using System;
using System.Collections.Generic;
using System.Text;

namespace RapidHDL
{
    class PriorityEncoder : TruthTableComponent
    {

        public NodeVector InputNodes;
        public NodeVector OutputNodes;


        public PriorityEncoder(Component poParentComponent, string psName, int piInputWidth, int piOutputWidth)
            : base(poParentComponent, psName)
        {
            InputNodes = this.CreateNodeVector("In", piInputWidth, NodeFlowType.Sink);
            OutputNodes = this.CreateNodeVector("Out", piOutputWidth, NodeFlowType.Source);

            this.GetTruthTable("PriorityEncoder", piInputWidth, piOutputWidth);
        }

        protected override void GenerateTruthTable()
        {
            int iInputWidth = InputNodes.Nodes.Count;
            int iOutputWidth = OutputNodes.Nodes.Count;

            string sInput;
            string sOutput;

            int iMax = 1;

            for (int iIdx = 0; iIdx < iInputWidth; iIdx++)
                iMax *= 2;

            int iOutput = 0;
            int iNextChange = 1;
            sOutput = Conversion.IntToBinaryString(0, iOutputWidth);
            
            for (int iIn=0; iIn < iMax; iIn++)
            {
                sInput = Conversion.IntToBinaryString(iIn, iInputWidth);
                if (iNextChange == iIn)
                {
                    sOutput = Conversion.IntToBinaryString(iOutput, iOutputWidth);
                    iNextChange *= 2;
                    iOutput++;
                }
                this.TruthTable.AddTableEntry(sInput, sOutput);
                //System.Console.WriteLine(sInput + " -> " + sOutput);
            }
        }

        public override bool TransformStructureToVerilog()
        {
            WriteVerilogLookupTable();
            return true;
        }
    }
}
